// pages/index/index.js
import {computeDis} from '../../utils/util.js'
var app = getApp()
let SCREEN_WIDTH = 750
let RATE = wx.getSystemInfoSync().screenHeight /wx.getSystemInfoSync().screenWidth
Page({

    /**
     * Page initial data
     */
    data: {
        ScreenTotalW: SCREEN_WIDTH,
        ScreenTotalH: SCREEN_WIDTH * RATE,
        showModal: false,
        activeTab:0,
        tabSwiperHeight: 0,
        scrollTop: null,
        navScrollLeft: 0,
        organizationDetailData: null,
        showServe: false,
        obj: Object,
        posName: "我的位置",
		organizations:[],
		orgImages:[],
        buyRecords:[],
        scanNum: 0,
        buyNum: 0,
        active:1,
        loadDone: false,
        canBuy: true,
		scene:"",
		needScroll: true,
		buyShowBlockNum: 1
    },
    /**
     * Lifecycle function--Called when page load
     */
    onLoad(options) {
		wx.hideHomeButton()
        if ("scene" in options) {
            app.globalData.scene = options["scene"]
		}
		console.log("index load option ", options)
        wx.showLoading({
          title: '加载中',
        })
        this.data.loadDone = false
        this.setData(
            {
                obj: app.getmallhead(),
				canBuy: wx.getStorageSync('canBuy'),
				needScroll: true
            }
        )
        this.getPageInfo()
    },
    async loginCon() {
		wx.showLoading({
			title: '加载中',
		})
		wx.redirectTo({
			url: '../login/login',
		})
    },
    async getPageInfo() {
        var orgInfo = app.getorginfo()
        var posInfo = app.getposinfo()
        if (posInfo && posInfo.posName) {
            this.setData({
                posName: posInfo.posName
            })
        }
        var url= app.globalData.BASE_URL + '/mallGetPageInfo'
        var data = {}
        let ret = await app.reqServer(url, data, 'GET')
		console.log(ret)
		if (ret) {
			var orgInfos = ret.organizationInfos
			var orgInfosWithDis = computeDis(posInfo, orgInfos)
			app.setorginfo(orgInfosWithDis)
			var price = ret.lessonPrice * 1.0/100
			app.settotalprice(price)
			this.setData(
				{
					organizations: orgInfosWithDis,
				}
			)
        	if (ret.buyUserInfos && ret.buyUserInfos.length > 0) {
            	this.getBuyerData(ret.buyUserInfos)
				if (ret.buyUserInfos.length > 5) {
					this.setData({
						buyShowBlockNum: 5
					})
				} else {
					this.setData(
						{
							buyShowBlockNum: ret.buyUserInfos.length
						}
					)
				}
			}
			if (ret.covers && ret.covers.length > 0) {
				this.setData({
					orgImages: ret.covers
				})
			}
			this.setData(
				{
					scanNum: ret.scanNum,
					buyNum: ret.buyerNum
				}
			)
			this.data.loadDone = true
			wx.hideLoading()
		}
    },
    updateLoc(res) {
        console.log(res)
        var orgInfo = app.getorginfo()
        if (!orgInfo) {
            wx.showToast({
                title: '登录已过期, 请重新登录',
                icon: 'none',
                duration: 1000,
            })
            setTimeout(
              function() {
                wx.reLaunch({
                  url: '../index/index',
                })
              }, 1000
            )
            return
        }
        var posInfo = {
            "longitude": parseFloat(res["longitude"]),
            "latitude":parseFloat(res["latitude"]),
            "posName" : res["name"]
        }
        var orgInfosWithDis = computeDis(posInfo, orgInfo)
        app.setorginfo(orgInfosWithDis)
        app.setposinfo(posInfo)
        this.setData(
            {
                organizations: orgInfosWithDis,
                posName: posInfo.posName,
            }
        )
        app.globalData.scene = this.data.scene
    },
    getBuyerData(data) {
		var buyRecords = []
        for (var i = 0; i < data.length; i++) {
            var buyRecord = {
                "name" : data[i].userName,
                "money" : data[i].money,
				"date": data[i].date,
				"avatarUrl": data[i].iconUrl
            }
            buyRecords.push(buyRecord)
		}
        this.setData(
            {
                "buyRecords": buyRecords
            }
        )
    },
    /**
     * Lifecycle function--Called when page is initially rendered
     */
    onReady() {

    },

    /**
     * Lifecycle function--Called when page show
     */
    onShow() {
		wx.hideHomeButton()
    },

    /**
     * Lifecycle function--Called when page hide
     */
    onHide() {
    },

    /**
     * Lifecycle function--Called when page unload
     */
    onUnload() {
    },

    /**
     * Page event handler function--Called when user drop down
     */
    onPullDownRefresh() {
    },

    /**
     * Called when page reach bottom
     */
    onReachBottom() {

    },

    /**
     * Called when user click on the top right corner to share
     */
    onShareAppMessage() {

    },
    scroll: function (e) {
		this.setData({ scrollTop: e.detail.scrollTop })
	},
    switchNav(event) {
        var cur = event.currentTarget.dataset.current; 
        //每个tab选项宽度占1/5
        var singleNavWidth = this.data.windowWidth / 5;
        //tab选项居中                            
        this.setData({
            navScrollLeft: (cur - 2) * singleNavWidth
        })      
        if (this.data.activeTab == cur) {
            return false;
        } else {
            this.setData({
                activeTab: cur
            })
        }
    },
    onSearchHome:function(e){
        var key = 'LMBBZ-EF3RL-ZYYPL-M3HD2-57323-WLBW3'
        var referer = 'mallxcx'
        // var location = JSON.stringify({
        //     latitude: 39.89631551,
        //     longitude: 116.323459711
        // });
        // wx.navigateTo({
        //     url: `plugin://chooseLocation/index?key=${key}&referer=${referer}`
        // });
		var that = this
		that.data.scene = app.globalData.scene
        wx.chooseLocation({
            success: (res) => {
                console.log(res)
                if (res["name"].length > 0) {
                    that.updateLoc(res)
                }
            },
            fail: () => {
                // 如果用wx.chooseLocation没有获取到地理位置，则需要获取当前的授权信息，判断是否有地理授权信息
                wx.getSetting({
                    success: (res) => {
                        var status = res.authSetting;
                        if (!status['scope.userLocation']) {
                            // 如果授权信息中没有地理位置的授权，则需要弹窗提示用户需要授权地理信息
                            wx.showModal({
                                title: "是否授权当前位置",
                                content: "需要获取您的地理位置，请确认授权，否则地图功能将无法使用",
                                success: (tip) => {
                                    if (tip.confirm) {
                                        // 如果用户同意授权地理信息，则打开授权设置页面，判断用户的操作
                                        wx.openSetting({
                                            success: (data) => {
                                                // 如果用户授权了地理信息在，则提示授权成功
                                                if (data.authSetting['scope.userLocation'] === true) {
                                                    wx.showToast({
                                                        title: "授权成功",
                                                        icon: "success",
                                                        duration: 1000
                                                    })
                                                    // 授权成功后，然后再次chooseLocation获取信息
                                                    wx.chooseLocation({success: (res) => {
                                                        that.updateLoc(res)
                                                    }
                                                    })
                                                } else {
                                                    wx.showToast({
                                                        title: "授权失败",
                                                        icon: "none",
                                                        duration: 1000
                                                    })
                                                }
                                            }
                                        })
                                    }
                                }
                            })
                        }
                    },
                    fail: (res) => {
                        wx.showToast({
                            title: "调用授权窗口失败",
                            icon: "none",
                            duration: 1000
                        })
                    }
                })
            }
        })
    },
    onTabClick(e) {
        const index = e.detail.index
        this.setData({ 
          activeTab: index 
        })
    },
    onChange(e) {
        this.tabsSwiperHeight();
        console.log("onChange " + this.data.activeTab)
    },
    onTapDetailClose() {
        this.setData({
			showModal:false,
			needScroll:true,
            organizationDetailData:null
        })
    },
    onTapToDetail: function(e) {
        var id = e.currentTarget.dataset.id;
        console.log("onTapToDetail curId is " + id);
        if (this.data.activeTab == 1) {
            this.setData(
                {
					showModal:true,
					needScroll:false,
                    organizationDetailData: this.data.organizations[id - 1]
                }
            )
        } else if (this.data.activeTab == 0 ) {
            this.setData(
                {
					showModal:true,
					needScroll:false
                }
            )
        }
    },
    onMineClick(e) {
        if (this.data.loadDone == false) {
            return
        }
		if (!app.getopenid()) {
			wx.reLaunch({
			  url: 'pages/index/index',
			})
			return
		}
        if (!app.getnickavatar()) {
            wx.showModal({
              title: '温馨提示',
              content: '换换小书包申请获取您的头像和昵称信息',
              complete: (res) => {
                if (res.cancel) {
                    
                }
                if (res.confirm) {
					wx.redirectTo({
						url: '../login/login',
					})
                }
              }
            })
        } else {
            wx.redirectTo({
			  url: '../my/my',
			})
        }
    },
    onServeClick(e) {
        this.setData(
            {
				showServe: true,
				needScroll:false
            }
        )
    },
    onPhoneClick() {
        wx.makePhoneCall({
		  phoneNumber: this.data.obj.phoneNumber,
		  fail(e) {
			  console.log(e)
		  }
        })
    },
    onServeClose(e) {
        this.setData(
            {
				showServe: false,
				needScroll:true
            }
        )
    },
    onServeBuy(e) {
        if (this.data.loadDone == false) {
            return
        }
        if (this.data.active === 1) {
			if (!app.getopenid()) {
				wx.reLaunch({
				  url: 'pages/index/index',
				})
				return
			}
			if (!app.getnickavatar()) {
                wx.showModal({
                    title: '温馨提示',
                    content: '换换小书包申请获取你的头像和昵称信息',
                    complete: (res) => {
						if (res.confirm) {
							wx.redirectTo({
								url: '../login/login',
							})
						}
                    }
                  })
            } else {
                wx.redirectTo({
                    url: '../select-lesson/select-lesson'
                })
            }
        }
    }
})